<template>
  <div class="departments-container">
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织结构" name="second">
          <!-- layout布局 -->
          <el-row type="flex" class="row-bg" justify="space-between">
            <el-col :span="6">深圳亚马逊科技股份分公司有限公司</el-col>
            <el-col :span="4">
              <span class="leader">负责人</span>
              <!-- 下拉菜单 -->
              <el-dropdown>
                <span class="el-dropdown-link">
                  下拉菜单<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item>
                    <el-button
                      type="text"
                      @click="showDialog('')"
                    >添加子部门</el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
          <!-- 分割线 -->
          <el-divider />
          <!-- 底部 -->
          <el-tree v-loading="loading" :data="departs">
            <template #default="{data}">
              <!-- layout布局 -->
              <el-row type="flex" style="width:100%" justify="space-between">
                <el-col :span="6">{{ data.name }}</el-col>
                <el-col :span="4">
                  <span class="leader">{{ data.manager }}</span>
                  <!-- 下拉菜单 -->
                  <el-dropdown>
                    <span class="el-dropdown-link">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item>
                        <!-- 文字按钮 -->
                        <el-button
                          type="text"
                          @click="showDialog(data.id)"
                        >添加子部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <!-- 文字按钮 -->
                        <el-button
                          type="text"
                          @click="editEnter(data.id)"
                        >查看部门</el-button>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <!-- 文字按钮 -->
                        <el-button
                          type="text"
                          @click="deleteBtn(data.id)"
                        >删除部门</el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </el-col>
              </el-row>
            </template>
          </el-tree>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- dilog弹框 -->

    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :show-close="false"
      @closed="closedHandel"
    >
      <el-form ref="depForm" :model="form" :rules="rules">
        <el-form-item
          label="部门名称"
          prop="name"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门编码"
          prop="code"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.code" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="部门负责人"
          prop="manager"
          :label-width="formLabelWidth"
        >
          <el-select
            v-model="form.manager"
            placeholder="请选择"
            @focus="getManagers"
          >
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :value="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="部门介绍"
          prop="introduce"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.introduce" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelForm">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 导入接口
import {
  getDepartments,
  addDepartments,
  getDepartmentById,
  editDepartment,
  delDepartmentById
} from '../../api/departments.js'
import { getEmployeeSimple } from '../../api/employees.js'
export default {
  name: 'Departments',
  data() {
    return {
      // 是否loading
      loading: false,
      dialogFormVisible: false, // 是否显示弹框
      // 表单数据
      form: {
        code: '',
        introduce: '',
        manager: '',
        name: '',
        pid: ''
      },
      formLabelWidth: '120px', // 左侧的高度
      activeName: 'second',
      managerList: [], // 管理员的信息
      rules: {
        name: [
          { required: true, message: '部门名字不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度为1-50个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 获取数据
              const res = await getDepartments()

              console.log('res:', res)
              const filterRes = res.depts.some(v => {
                if (this.form.id) {
                  // 编辑id不相等但是value相等
                  if (value === v.name && this.form.id !== v.id) {
                    return true
                  } else {
                    // 新增
                    if (value === v.name) {
                      return false
                    }
                  }
                }
              })
              if (filterRes.length === 0) {
                callback() // 不重复
              } else {
                callback(new Error('名字重复，请重新输入'))
              }
            },
            trigger: 'blur'
          }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度为1-50个字符', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '长度为1-50个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              const res = await getDepartments()
              console.log(res)
              const filterRes = res.depts.some(v => {
                if (this.form.id) {
                  // 编辑
                  if (value === v.code && this.form.id !== v.id) {
                    return true
                  } else {
                    // 新增
                    if (value === v.code) {
                      return false
                    }
                  }
                }
              })
              if (filterRes.length === 0) {
                callback()
              } else {
                callback(new Error('编码重复，请重新输入'))
              }
            },
            trigger: 'blur'
          }
        ]
      },
      // tree插件
      departs: [
        {
          name: '总裁办',
          manager: '曹操',
          children: [{ name: '董事会', manager: '曹丕' }]
        },
        { name: '行政部', manager: '刘备' },
        { name: '人事部', manager: '孙权' }
      ]
    }
  },
  computed: {
    title() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getData()
  },
  methods: {
    // 弹框关闭回调函数
    closedHandel() {
      if (this.form.id) {
        this.form = {
          code: '',
          introduce: '',
          manager: '',
          name: '',
          pid: ''
        }
      } else {
        // 上一次是新增，不清空
      }
    },
    // 删除部门
    deleteBtn(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const delRes = await delDepartmentById(id)
          console.log(delRes)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑部门
    async editEnter(id) {
      const res = await getDepartmentById(id)
      console.log('res:', res)
      this.form = res
      this.dialogFormVisible = true
    },

    // 递归优化
    async getData() {
      this.loading = true
      const res = await getDepartments()
      console.log('res:', res)
      // 递归 必须有个函数 基于给定的 pid 返回满足条件的数组
      function formatData(list, pid) {
        return list.filter(v => {
          if (v.pid === pid) {
            // 筛选子节点的条件是 循环数组的 每一项的 pid 和 当前这一项的 id 相等
            v.children = formatData(list, v.id)
            return true
          } else {
            return false
          }
        })
      }
      // 第一次筛选 pid 是 ''
      const treeRes = formatData(res.depts, '')
      // 直接赋值即可
      this.departs = treeRes
      this.loading = false
      // // 筛选pid为‘’的顶级节点
      // const timeTree = res.depts.filter(v => {
      //   if (v.pid === '') {
      //     return true
      //   } else {
      //     return false
      //   }
      // })
      // timeTree.forEach(rV => {
      //   const children = res.depts.filter(v => {
      //     if (v.pid === rV.id) {
      //       return true
      //     } else {
      //       return false
      //     }
      //   })
      //   rV.children = children
      // })
      // this.departs = timeTree
    },

    // 最顶部的添加(按钮)
    showDialog(pid) {
      // 给表单直接存入
      this.form.pid = pid
      this.dialogFormVisible = true
    },
    // 取消按钮
    cancelForm() {
      this.$refs.depForm.resetFields()
    },

    // 确认按钮
    submitForm() {
      this.$refs.depForm.validate(async valid => {
        if (valid) {
          if (this.form.id) {
            // 编辑  form中没有id
            await editDepartment(this.form)
            this.$message.success('编辑成功')
          } else {
            // 新增
            // 校验通过，提交数据
            await addDepartments(this.form)
            this.$message.success('增加成功')
          }
          // 关闭弹框
          this.dialogFormVisible = false
          // 刷新数据
          this.getData()
          // 清空表单
          this.$refs.depForm.resetFields()
          this.form = {
            code: '',
            introduce: '',
            manager: '',
            name: '',
            pid: ''
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 管理员信息
    async getManagers() {
      const res = await getEmployeeSimple()
      console.log('res:', res)
      this.managerList = res
    }
  }
}
</script>

<style lang="scss">
.departments-container {
  padding: 20px;
  background-color: #f0f2f5;
  font-size: 14px;
  .leader {
    margin-right: 5px;
  }
  .el-tabs__content {
    padding: 20px 90px;
  }
  .el-divider {
    margin-top: 10px;
  }
  .el-col-4 {
    text-align: right;
  }
}
</style>
